namespace et{
    /** 白鹭资源加载 */
    export class egretRes {
        private static ResList: {[name: string]: ResEvent} = {};

        /**
         * 资源添加至预加载列表
         * @param name 资源名
         * @param progressFunc 资源进度事件
         * @param completeFunc 资源加载完成事件
         * @param errorFunc 资源加载错误事件
         */
        public static pushRes(name: string, progressFunc?: Function, completeFunc?: Function, errorFunc?: Function){
            let resEvent = new ResEvent();
            resEvent.progress = progressFunc;
            resEvent.complete = completeFunc;
            resEvent.error = errorFunc;

            if (this.ResList[name]){
                throw "资源组重复添加" + name;
            }

            this.ResList[name] = resEvent;
        }

        /**
         * 开始加载资源
         * @param clearRes 加载完是否移除加载列表
         */
        public static async loadRes(clearRes: boolean = false){
            for (let k in this.ResList){
                let resEvent = this.ResList[k];
                await this.registerResEvent(k, resEvent);

                if (clearRes){
                    delete this.ResList[k];
                }
            }
        }

        private static async registerResEvent(resName: string, resEvent: ResEvent){
            let onResProgress = (event: RES.ResourceEvent)=>{ 
                if (resEvent.progress)
                    resEvent.progress(event) 
            };
            let onResError = (event: egret.Event)=>{ 
                if (resEvent.error)
                    resEvent.error(event) 
            };
            let onResComplete = (event: egret.Event)=>{ 
                if (resEvent.complete)
                    resEvent.complete(event) 
            };

            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, onResProgress, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, onResError, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, onResComplete, this);

            RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, onResProgress, this);
            RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, onResError, this);
            RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, onResComplete, this);

            /** 如果资源组未加载 */
            if (!RES.isGroupLoaded(resName)){
                await RES.loadGroup(resName);
            }
        }
    }

    export class ResEvent{
        progress: Function;
        complete: Function;
        error: Function;
    }
}